home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1996 February / EnigmA AMIGA RUN 04 (1996)(G.R. Edizioni)(IT)[!][issue 1996-02][Skylink CD III].iso / earcd / midi / midifl12.lha / midifile.new / midifile.c < prev    next >
C/C++ Source or Header  |  1995-08-27  |  32KB  |  1,317 lines

  1.  
  2. /*
  3.  * midifile 1.11
  4.  *
  5.  * Read and write a MIDI file.  Externally-assigned function pointers are
  6.  * called upon recognizing things in the file.
  7.  *
  8.  * Original release ?
  9.  * June 1989 - Added writing capability, M. Czeiszperger.
  10.  *
  11.  *          The file format implemented here is called
  12.  *          Standard MIDI Files, and is part of the Musical
  13.  *          instrument Digital Interface specification.
  14.  *          The spec is avaiable from:
  15.  *
  16.  *               International MIDI Association
  17.  *               5316 West 57th Street
  18.  *               Los Angeles, CA 90056
  19.  *
  20.  *          An in-depth description of the spec can also be found
  21.  *          in the article "Introducing Standard MIDI Files", published
  22.  *          in Electronic Musician magazine, April, 1989.
  23.  *
  24.  * February 1993 - Minor adjustments, Greg Lee:
  25.  *    (1) can now set the global variable Mf_interactive to 1 to prevent the
  26.  *        reading functions from looking for file and track headers
  27.  *    (2) can now write system exclusive data with
  28.  *        mf_write_midi_event(delta_time, system_exlusive, 0, data, size)
  29.  *    (3) changed definition of 'sequencer_specific' in midifile.h to 0x7f
  30.  *    (4) changed mf_write_tempo to take additional delta_time as first argument
  31.  *        (since delta need not be zero)
  32.  *    (5) added function mf_write_seqnum(unsigned long delta_time, unsigned seqnum)
  33.  *    (6) changed mf_write_midi_event to use running status
  34.  *    (7) removed the code to write an end of track meta event automatically
  35.  *        -- this must now be done by the user of the library (I changed
  36.  *        it because I need to be able to control the time delta of this
  37.  *         meta event)
  38.  *    (8) added global variables Mf_division, Mf_currtempo, Mf_realtime, which
  39.  *        are updated by the reading functions.  Mf_realtime is useful,
  40.  *        because Mf_currtime does not really measure time at all, since
  41.  *        its units change value at every tempo change.  Mf_realtime is
  42.  *        the midi-time elapsed in units of 1/16 of a centisecond (but it
  43.  *        does not handle smpte times)
  44.  *    (9) maintains a history of tempo settings to update Mf_currtempo,
  45.  *        to handle tempo tracks.
  46.  *    (10) if there is an Mf_error function, the error routine no longer
  47.  *        exits, leaving it to the application to do this.
  48.  *    (11) chanmessage skips over invalid c1 command bytes > 127 and
  49.  *        adjusts invalid c2 argument byte > 127 to 127.
  50.  *    (12) readmt returns EOF when it encounters a 0 or 0x1a byte instead of an expected
  51.  *        header string (some midi files have padding at end).
  52.  */
  53.  
  54. #define MAXINT                  0x7FFFFFFF
  55.  
  56. #define NO_LC_DEFINES
  57. #include"midifile.h"
  58. #ifdef NO_LC_DEFINES
  59. #define system_exclusive          0xf0
  60. #define    meta_event        0xFF
  61. #define    set_tempo        0x51
  62. #define lowerbyte(x) ((unsigned char)(x & 0xff))
  63. #define upperbyte(x) ((unsigned char)((x & 0xff00)>>8))
  64. #endif
  65.  
  66. #define NULLFUNC 0
  67. #define NULL 0
  68.  
  69. #define THINK
  70.  
  71. #include <stdlib.h>
  72.  
  73. #include <stdio.h>
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82. /* Functions to be called while processing the MIDI file. */
  83. int (*Mf_getc) (void) = NULLFUNC;
  84. int (*Mf_error) (char *) = NULLFUNC;
  85. int (*Mf_header) (int,int,int) = NULLFUNC;
  86. int (*Mf_trackstart) (void) = NULLFUNC;
  87. int (*Mf_trackend) (void) = NULLFUNC;
  88. int (*Mf_noteon) (int,int,int) = NULLFUNC;
  89. int (*Mf_noteoff) (int,int,int) = NULLFUNC;
  90. int (*Mf_pressure) (int,int,int) = NULLFUNC;
  91. int (*Mf_parameter) (int,int,int) = NULLFUNC;
  92. int (*Mf_pitchbend) (int,int,int) = NULLFUNC;
  93. int (*Mf_program) (int,int) = NULLFUNC;
  94. int (*Mf_chanpressure) (int,int) = NULLFUNC;
  95. int (*Mf_sysex) (int,char *) = NULLFUNC;
  96. int (*Mf_arbitrary) (int,int) = NULLFUNC;
  97. int (*Mf_metamisc) (int,int,char *) = NULLFUNC;
  98. int (*Mf_seqnum) (int) = NULLFUNC;
  99. int (*Mf_eot) (void) = NULLFUNC;
  100. int (*Mf_smpte) (int,int,int,int,int) = NULLFUNC;
  101. int (*Mf_tempo) (long) = NULLFUNC;
  102. int (*Mf_timesig) (int,int,int,int) = NULLFUNC;
  103. int (*Mf_keysig) (int,int) = NULLFUNC;
  104. int (*Mf_seqspecific) (int,int,char *) = NULLFUNC;
  105. int (*Mf_text) (int,int,char *) = NULLFUNC;
  106.  
  107. /* Functions to implement in order to write a MIDI file */
  108. int (*Mf_putc) (char) = NULLFUNC;
  109. int (*Mf_writetrack) (int) = NULLFUNC;
  110. int (*Mf_writetempotrack) (void) = NULLFUNC;
  111.  
  112. int Mf_nomerge = 0;        /* 1 => continue'ed system exclusives are */
  113.  /* not collapsed. */
  114. int Mf_interactive = 0;        /* 1 => file and track headers are not required */
  115. unsigned long Mf_currtime = 0L;    /* current time in delta-time units */
  116. unsigned long Mf_realtime = 0L;    /* current time in 1/16 centisecond-time units */
  117. static double Mf_f_realtime = 0.0;/* as above, floating */
  118. static double old_f_realtime = 0.0;
  119. int Mf_division = 96;
  120. unsigned long Mf_currtempo = 500000;
  121. static unsigned long old_currtempo = 500000;
  122. static unsigned long old_realtime = 0;
  123. static unsigned long old_currtime = 0;
  124. static unsigned long revised_time = 0;
  125. static unsigned long tempo_change_time = 0;
  126.  
  127. #define MAX_HISTORY 512
  128. static unsigned long tempo_history[MAX_HISTORY];
  129. static unsigned long tempo_history_time[MAX_HISTORY];
  130. static int tempo_history_count = 0;
  131.  
  132. /* private stuff */
  133. static long Mf_toberead = 0L;
  134. static long Mf_numbyteswritten = 0L;
  135.  
  136. static long readvarinum ();
  137. static long read32bit ();
  138. static long to32bit ();
  139. static int read16bit ();
  140. static int to16bit ();
  141. static char *msg ();
  142. static void readheader ();
  143. static int readtrack ();
  144. static void badbyte ();
  145. static void metaevent ();
  146. static void sysex ();
  147. static void chanmessage ();
  148. static void msginit ();
  149. static int msgleng ();
  150. static void msgadd ();
  151. static void biggermsg ();
  152. static int eputc (unsigned char c);
  153.  
  154. double mf_ticks2sec (unsigned long ticks, int division, unsigned long tempo);
  155.  
  156. void mf_write_tempo ();
  157. void mf_write_seqnum ();
  158. void WriteVarLen ();
  159.  
  160. /* mfread : returns <void> with input variables:
  161.  * void:
  162.  */
  163. void mfread (void)
  164. {
  165.   if (Mf_getc == NULLFUNC)
  166. mferror ("mfread() called without setting Mf_getc");
  167.  
  168.   readheader ();
  169. while (readtrack ())
  170. ;
  171. }
  172.  
  173. /* ------------------------------------------------------------------------ */
  174.  
  175. /* for backward compatibility with the original lib */
  176. /* midifile : returns <void> with input variables:
  177.  * void:
  178.  */
  179. void midifile (void)
  180. {
  181.   mfread ();
  182. }
  183.  
  184. /* ------------------------------------------------------------------------ */
  185.  
  186. /* s:  read through the "MThd" or "MTrk" header string
  187.  */
  188. /* readmt : returns <static int> with input variables:
  189.  * s:
  190.  */
  191. static int readmt (char *s)
  192. {
  193.   int n = 0;
  194.   char *p = s;
  195.   int c;
  196.  
  197.   while (n++ < 4 && (c = (*Mf_getc) ()) != EOF) {
  198.  
  199.     if (c != *p++) {
  200.  
  201.           char buff[32];
  202.           if (!c) return(EOF);
  203.           if (c == 0x1a) return(EOF);
  204.           (void) strcpy (buff, "expecting ");
  205.           (void) strcat (buff, s);
  206.           mferror (buff);
  207.           break;
  208.         }
  209.     }
  210.   return (c);
  211. }
  212.  
  213. /* ------------------------------------------------------------------------ */
  214.  
  215. /*  read a single character and abort on EOF */
  216. /* egetc : returns <static int> with input variables:
  217.  * void:
  218.  */
  219. static int egetc (void)
  220. {
  221.   int c = (*Mf_getc) ();
  222.  
  223.   if (c == EOF)
  224. mferror ("premature EOF");
  225.   Mf_toberead--;
  226.   return (c);
  227. }
  228.  
  229. /* ------------------------------------------------------------------------ */
  230.  
  231. /*  read a header chunk */
  232. /* readheader : returns <static void> with input variables:
  233.  * void:
  234.  */
  235. static void readheader (void)
  236. {
  237.   int format, ntrks, division;
  238.  
  239.  
  240.   Mf_division = 96;
  241.   Mf_currtempo = 500000;
  242.   old_currtempo = 500000;
  243.   tempo_history_count = 0;
  244.   tempo_history[tempo_history_count] = Mf_currtempo;
  245.   tempo_history_time[tempo_history_count] = 0;
  246.  
  247.   if (Mf_interactive) {
  248.  
  249.     Mf_toberead = 0;
  250.     format = 0;
  251.     ntrks = 1;
  252.     division = 96;
  253.     }
  254.   else {
  255.  
  256.     if (readmt ("MThd") == EOF)
  257.     return;
  258.  
  259.     Mf_toberead = read32bit ();
  260.     format = read16bit ();
  261.     ntrks = read16bit ();
  262.     Mf_division = division = read16bit ();
  263.     }
  264.  
  265.   if (Mf_header)
  266. (*Mf_header) (format, ntrks, division);
  267.  
  268.   /* flush any extra stuff, in case the length of header is not 6 */
  269.   while (Mf_toberead > 0)
  270. (void) egetc ();
  271. }
  272.  
  273. /* ------------------------------------------------------------------------ */
  274.  
  275.  
  276. /*#define DEBUG_TIMES*/
  277. /* find_tempo: returns <static unsigned long> with input variables:
  278.  * void:
  279.  */
  280. static unsigned long find_tempo(void)
  281. {
  282.   int i;
  283.   unsigned long old_tempo = Mf_currtempo;
  284.   unsigned long new_tempo = Mf_currtempo;
  285.  
  286.   for (i = 0; i <= tempo_history_count; i++) {
  287.     if (tempo_history_time[i] <= Mf_currtime) old_tempo = tempo_history[i];
  288.     new_tempo = tempo_history[i];
  289.     if (tempo_history_time[i] > revised_time) break;
  290.       }
  291.   if (i > tempo_history_count || tempo_history_time[i] > Mf_currtime) {
  292. #ifdef DEBUG_TIMES
  293.     printf("[past %d, old_tempo %d]\n", tempo_history_time[i], old_tempo);
  294. #endif
  295.     revised_time = Mf_currtime;
  296.     return(old_tempo);
  297.       }
  298.   tempo_change_time = revised_time = tempo_history_time[i];
  299. #ifdef DEBUG_TIMES
  300. printf("[revised_time %d, new_tempo %d]\n", revised_time, new_tempo);
  301. #endif
  302.   return(new_tempo);
  303. }
  304.  
  305. /* ------------------------------------------------------------------------ */
  306.  
  307. /*  read a track chunk */
  308. /* readtrack : returns <static int> with input variables:
  309.  * void:
  310.  */
  311. static int readtrack (void)
  312. {
  313.   /* This array is indexed by the high half of a status byte.  It's */
  314.   /* value is either the number of bytes needed (1 or 2) for a channel */
  315.   /* message, or 0 (meaning it's not  a channel message). */
  316.   static int chantype[] =
  317.   {
  318.     0, 0, 0, 0, 0, 0, 0, 0,    /* 0x00 through 0x70 */
  319.     2, 2, 2, 2, 1, 1, 2, 0    /* 0x80 through 0xf0 */
  320.       }
  321. ;
  322.   long lookfor;
  323.   int c, c1, type;
  324.   int sysexcontinue = 0;    /* 1 if last message was an unfinished sysex */
  325.   int running = 0;        /* 1 when running status used */
  326.   int status = 0;        /* status value (e.g. 0x90==note-on) */
  327.   int needed;
  328.  
  329.   if (Mf_interactive) {
  330.  
  331.     Mf_toberead = MAXINT;
  332.     }
  333.   else {
  334.  
  335.     if (readmt ("MTrk") == EOF)
  336.     return (0);
  337.  
  338.     Mf_toberead = read32bit ();
  339.     }
  340.   Mf_currtime = Mf_realtime = 0;
  341.   Mf_f_realtime = old_f_realtime = 0;
  342.   old_currtime = old_realtime = 0;
  343.   Mf_currtempo = find_tempo();
  344.  
  345.   if (Mf_trackstart)
  346. (*Mf_trackstart) ();
  347.  
  348.   while (Mf_interactive || Mf_toberead > 0) {
  349.  
  350.  
  351.     if (Mf_interactive)
  352.     Mf_currtime += 1;
  353.     else {
  354.  
  355.           double delta_secs;
  356.           unsigned long delta_ticks = readvarinum ();
  357.           revised_time = Mf_currtime;
  358.           Mf_currtime += delta_ticks;    /* delta time */
  359.  
  360.         /*
  361.          * Step through each tempo change from old_currtime up to now,
  362.          * revising Mf_realtime after each change.
  363.          */
  364.  
  365.           while (revised_time < Mf_currtime) {
  366.             unsigned long save_time = revised_time;
  367.             unsigned long save_tempo = Mf_currtempo;
  368.             Mf_currtempo = find_tempo();
  369.  
  370.             if (Mf_currtempo != old_currtempo) {
  371.                 old_currtempo = Mf_currtempo;
  372.                 old_realtime = Mf_realtime;
  373.                 if (revised_time != tempo_change_time) {
  374.                     old_f_realtime = Mf_f_realtime;
  375.                     old_currtime = save_time;
  376.                     }
  377.                 delta_secs = mf_ticks2sec (revised_time-old_currtime, Mf_division, save_tempo);
  378. #ifdef DEBUG_TIMES
  379.                 printf("d(rev %d - old %d, div %d, tempo %d) = %.3f\n",
  380.                 revised_time, old_currtime, Mf_division, save_tempo, delta_secs * 1600.0);
  381. #endif
  382.                 Mf_f_realtime = old_f_realtime + delta_secs * 1600.0;
  383.                 Mf_realtime = (unsigned long)(0.5 + Mf_f_realtime);
  384. #ifdef DEBUG_TIMES
  385.                 printf("\tt=%d ticks ( = %d csec/16 < old %.2f + %.2f)\n", Mf_currtime, Mf_realtime, 
  386.                 old_f_realtime, delta_secs * 1600.0);
  387. #endif
  388.                 if (revised_time == tempo_change_time) {
  389.                     old_currtime = revised_time;
  390.                     old_f_realtime = Mf_f_realtime;
  391.                     }
  392.                 }
  393.             else {
  394.                 delta_secs = mf_ticks2sec (revised_time-old_currtime, Mf_division, Mf_currtempo);
  395. #ifdef DEBUG_TIMES
  396.                 printf("d(rev %d - old %d, div %d, tempo %d) = %.3f\n",
  397.                 revised_time, old_currtime, Mf_division, Mf_currtempo, delta_secs * 1600.0);
  398. #endif
  399.                 Mf_f_realtime = old_f_realtime + delta_secs * 1600.0;
  400.                 Mf_realtime = (unsigned long)(0.5 + Mf_f_realtime);
  401. #ifdef DEBUG_TIMES
  402.                 printf("\tt=%d ticks ( = %d csec/16 < old %.2f + %.2f)\n", Mf_currtime, Mf_realtime, 
  403.                 old_f_realtime, delta_secs * 1600.0);
  404. #endif
  405.                 }
  406.  
  407.  
  408.               }
  409.         }
  410.  
  411.     c = egetc ();
  412.  
  413.     if (sysexcontinue && c != 0xf7)
  414.     mferror ("didn't find expected continuation of a sysex");
  415.  
  416.     if ((c & 0x80) == 0) {
  417.         /* running status? */
  418.           if (status == 0)
  419.         mferror ("unexpected running status");
  420.           running = 1;
  421.         }
  422.     else {
  423.  
  424.           status = c;
  425.           running = 0;
  426.         }
  427.  
  428.     needed = chantype[(status >> 4) & 0xf];
  429.  
  430.     if (needed) {
  431.         /* ie. is it a channel message? */
  432.  
  433.           if (running)
  434.         c1 = c;
  435.           else
  436.         c1 = egetc ();
  437.           chanmessage (status, c1, (needed > 1) ? egetc () : 0);
  438.           continue;;
  439.         }
  440.  
  441.     switch (c) {
  442.  
  443.  
  444.         case 0xff:        /* meta event */
  445.  
  446.           type = egetc ();
  447.           lookfor = Mf_toberead - readvarinum ();
  448.           msginit ();
  449.  
  450.           while (Mf_toberead > lookfor)
  451.         msgadd (egetc ());
  452.  
  453.           metaevent (type);
  454.           break;
  455.  
  456.         case 0xf0:        /* start of system exclusive */
  457.  
  458.           lookfor = Mf_toberead - readvarinum ();
  459.           msginit ();
  460.           msgadd (0xf0);
  461.  
  462.           while (Mf_toberead > lookfor)
  463.         msgadd (c = egetc ());
  464.  
  465.           if (c == 0xf7 || Mf_nomerge == 0)
  466.         sysex ();
  467.           else
  468.         sysexcontinue = 1;    /* merge into next msg */
  469.           break;
  470.  
  471.         case 0xf7:        /* sysex continuation or arbitrary stuff */
  472.  
  473.           lookfor = Mf_toberead - readvarinum ();
  474.  
  475.           if (!sysexcontinue)
  476.         msginit ();
  477.  
  478.           while (Mf_toberead > lookfor)
  479.         msgadd (c = egetc ());
  480.  
  481.           if (!sysexcontinue) {
  482.  
  483.             if (Mf_arbitrary)
  484.             (*Mf_arbitrary) ((int)msgleng (),(int) msg ());
  485.             }
  486.           else if (c == 0xf7) {
  487.  
  488.             sysex ();
  489.             sysexcontinue = 0;
  490.             }
  491.           break;
  492.     default:
  493.           badbyte (c);
  494.           break;
  495.         }
  496.     }
  497.   if (Mf_trackend)
  498. (*Mf_trackend) ();
  499.   return (1);
  500. }
  501.  
  502. /* ------------------------------------------------------------------------ */
  503.  
  504. /* badbyte : returns <static void> with input variables:
  505.  * c:
  506.  */
  507. static void badbyte (int c)
  508. {
  509.   char buff[32];
  510.  
  511.   (void) sprintf (buff, "unexpected byte: 0x%02x", c);
  512.   mferror (buff);
  513. }
  514.  
  515. /* ------------------------------------------------------------------------ */
  516.  
  517. /* metaevent : returns <static void> with input variables:
  518.  * type:
  519.  */
  520. static void metaevent (int type)
  521. {
  522.   int leng = msgleng ();
  523.   char *m = msg ();
  524.  
  525.   switch (type) {
  526.  
  527.     case 0x00:
  528.     if (Mf_seqnum)
  529.     (*Mf_seqnum) (to16bit (m[0], m[1]));
  530.     break;
  531.     case 0x01:            /* Text event */
  532.     case 0x02:            /* Copyright notice */
  533.     case 0x03:            /* Sequence/Track name */
  534.     case 0x04:            /* Instrument name */
  535.     case 0x05:            /* Lyric */
  536.     case 0x06:            /* Marker */
  537.     case 0x07:            /* Cue point */
  538.     case 0x08:
  539.     case 0x09:
  540.     case 0x0a:
  541.     case 0x0b:
  542.     case 0x0c:
  543.     case 0x0d:
  544.     case 0x0e:
  545.     case 0x0f:
  546.     /* These are all text events */
  547.     if (Mf_text)
  548.     (*Mf_text) (type, leng, m);
  549.     break;
  550.     case 0x2f:            /* End of Track */
  551.     if (Mf_eot)
  552.     (*Mf_eot) ();
  553.     break;
  554.     case 0x51:            /* Set tempo */
  555.     if (Mf_tempo)
  556.     (*Mf_tempo) (Mf_currtempo = to32bit (0, m[0], m[1], m[2]));
  557.     if (tempo_history[tempo_history_count] == Mf_currtempo) break;
  558.     if (tempo_history_time[tempo_history_count] > Mf_currtime) break;
  559.     if (tempo_history_count < MAX_HISTORY - 1) tempo_history_count++;
  560.     tempo_history[tempo_history_count] = Mf_currtempo;
  561.     tempo_history_time[tempo_history_count] = Mf_currtime;
  562.     break;
  563.     case 0x54:
  564.     if (Mf_smpte)
  565.     (*Mf_smpte) (m[0], m[1], m[2], m[3], m[4]);
  566.     break;
  567.     case 0x58:
  568.     if (Mf_timesig)
  569.     (*Mf_timesig) (m[0], m[1], m[2], m[3]);
  570.     break;
  571.     case 0x59:
  572.     if (Mf_keysig)
  573.     (*Mf_keysig) (m[0], m[1]);
  574.     break;
  575.     case 0x7f:
  576.     if (Mf_seqspecific)
  577.     (*Mf_seqspecific) ((int)leng, (int)m,(char *)NULL);
  578.     break;
  579. default:
  580.     if (Mf_metamisc)
  581.     (*Mf_metamisc) (type, leng, m);
  582.     }
  583. }
  584.  
  585. /* ------------------------------------------------------------------------ */
  586.  
  587. /* sysex : returns <static void> with input variables:
  588.  * void:
  589.  */
  590. static void sysex (void)
  591. {
  592.   if (Mf_sysex)
  593. (*Mf_sysex) (msgleng (), msg ());
  594. }
  595.  
  596. /* ------------------------------------------------------------------------ */
  597.  
  598. /* chanmessage : returns <static void> with input variables:
  599.  * status:
  600.  * c1:
  601.  * c2:
  602.  */
  603. static void chanmessage (
  604.   int status,
  605.   int c1,
  606.   int c2)
  607. {
  608.   int chan = status & 0xf;
  609.  
  610.   /* I found a midi file with Mod Wheel values 128. --gl */
  611.  
  612.   if (c1 > 127) /*mferror("chanmessage: bad c1") ??*/ return;
  613.   if (c2 > 127) c2 = 127;
  614.  
  615.   switch (status & 0xf0) {
  616.  
  617.     case 0x80:
  618.     if (Mf_noteoff)
  619.     (*Mf_noteoff) (chan, c1, c2);
  620.     break;
  621.     case 0x90:
  622.     if (Mf_noteon)
  623.     (*Mf_noteon) (chan, c1, c2);
  624.     break;
  625.     case 0xa0:
  626.     if (Mf_pressure)
  627.     (*Mf_pressure) (chan, c1, c2);
  628.     break;
  629.     case 0xb0:
  630.     if (Mf_parameter)
  631.     (*Mf_parameter) (chan, c1, c2);
  632.     break;
  633.     case 0xe0:
  634.     if (Mf_pitchbend)
  635.     (*Mf_pitchbend) (chan, c1, c2);
  636.     break;
  637.     case 0xc0:
  638.     if (Mf_program)
  639.     (*Mf_program) (chan, c1);
  640.     break;
  641.     case 0xd0:
  642.     if (Mf_chanpressure)
  643.     (*Mf_chanpressure) (chan, c1);
  644.     break;
  645.     }
  646. }
  647.  
  648. /* ------------------------------------------------------------------------ */
  649.  
  650. /* readvarinum - read a varying-length number, and return the */
  651. /* number of characters it took. */
  652.  
  653. /* readvarinum : returns <static long> with input variables:
  654.  * void:
  655.  */
  656. static long readvarinum (void)
  657. {
  658.   long value;
  659.   int c;
  660.  
  661.   c = egetc ();
  662.   value = c;
  663.   if (c & 0x80) {
  664.  
  665.     value &= 0x7f;
  666.     do {
  667.  
  668.           c = egetc ();
  669.           value = (value << 7) + (c & 0x7f);
  670.         }
  671.     while (c & 0x80);
  672.     }
  673.   return (value);
  674. }
  675.  
  676. /* ------------------------------------------------------------------------ */
  677.  
  678. /* to32bit : returns <static long> with input variables:
  679.  * c1:
  680.  * c2:
  681.  * c3:
  682.  * c4:
  683.  */
  684. static long to32bit (
  685.   int c1,
  686.   int c2,
  687.   int c3,
  688.   int c4)
  689. {
  690.   long value = 0L;
  691.  
  692.   value = (c1 & 0xff);
  693.   value = (value << 8) + (c2 & 0xff);
  694.   value = (value << 8) + (c3 & 0xff);
  695.   value = (value << 8) + (c4 & 0xff);
  696.   return (value);
  697. }
  698.  
  699. /* ------------------------------------------------------------------------ */
  700.  
  701. /* to16bit : returns <static int> with input variables:
  702.  * c1:
  703.  * c2:
  704.  */
  705. static int to16bit (
  706.   int c1,
  707.   int c2)
  708. {
  709.   return ((c1 & 0xff) << 8) + (c2 & 0xff);
  710. }
  711.  
  712. /* ------------------------------------------------------------------------ */
  713.  
  714. /* read32bit : returns <static long> with input variables:
  715.  * void:
  716.  */
  717. static long read32bit (void)
  718. {
  719.   int c1, c2, c3, c4;
  720.  
  721.   c1 = egetc ();
  722.   c2 = egetc ();
  723.   c3 = egetc ();
  724.   c4 = egetc ();
  725.   return to32bit (c1, c2, c3, c4);
  726. }
  727.  
  728. /* ------------------------------------------------------------------------ */
  729.  
  730. /* read16bit : returns <static int> with input variables:
  731.  * void:
  732.  */
  733. static int read16bit (void)
  734. {
  735.   int c1, c2;
  736.   c1 = egetc ();
  737.   c2 = egetc ();
  738.   return to16bit (c1, c2);
  739. }
  740.  
  741. /* ------------------------------------------------------------------------ */
  742.  
  743. /* static */
  744. /* mferror : returns <void> with input variables:
  745.  * s:
  746.  */
  747. void mferror (char *s)
  748. {
  749.   if (Mf_error)
  750. (*Mf_error) (s);
  751.   else exit (1);
  752. }
  753.  
  754. /* ------------------------------------------------------------------------ */
  755.  
  756. /* The code below allows collection of a system exclusive message of */
  757. /* arbitrary length.  The Msgbuff is expanded as necessary.  The only */
  758. /* visible data/routines are msginit(), msgadd(), msg(), msgleng(). */
  759.  
  760. #define MSGINCREMENT 128
  761. static char *Msgbuff = NULL;    /* message buffer */
  762. static int Msgsize = 0;        /* Size of currently allocated Msg */
  763. static int Msgindex = 0;    /* index of next available location in Msg */
  764.  
  765. /* msginit : returns <static void> with input variables:
  766.  * void:
  767.  */
  768. static void msginit (void)
  769. {
  770.   Msgindex = 0;
  771. }
  772.  
  773. /* ------------------------------------------------------------------------ */
  774.  
  775. /* * msg : returns <static char> with input variables:
  776.  * void:
  777.  */
  778. static char * msg (void)
  779. {
  780.   return (Msgbuff);
  781. }
  782.  
  783. /* ------------------------------------------------------------------------ */
  784.  
  785. /* msgleng : returns <static int> with input variables:
  786.  * void:
  787.  */
  788. static int msgleng (void)
  789. {
  790.   return (Msgindex);
  791. }
  792.  
  793. /* ------------------------------------------------------------------------ */
  794.  
  795. /* msgadd : returns <static void> with input variables:
  796.  * c:
  797.  */
  798. static void msgadd (int c)
  799. {
  800.   /* If necessary, allocate larger message buffer. */
  801.   if (Msgindex >= Msgsize)
  802. biggermsg ();
  803.   Msgbuff[Msgindex++] = c;
  804. }
  805.  
  806. /* ------------------------------------------------------------------------ */
  807.  
  808. /* biggermsg : returns <static void> with input variables:
  809.  * void:
  810.  */
  811. static void biggermsg (void)
  812. {
  813. /*     char *malloc(); */
  814.   char *newmess;
  815.   char *oldmess = Msgbuff;
  816.   int oldleng = Msgsize;
  817.  
  818.   Msgsize += MSGINCREMENT;
  819.   newmess = (char *) malloc ((unsigned) (sizeof (char) * Msgsize));
  820.  
  821.   if (newmess == NULL)
  822. mferror ("malloc error!");
  823.  
  824.   /* copy old message into larger new one */
  825.   if (oldmess != NULL) {
  826.  
  827.     register char *p = newmess;
  828.     register char *q = oldmess;
  829.     register char *endq = &oldmess[oldleng];
  830.  
  831.     for (; q != endq; p++, q++)
  832.     *p = *q;
  833.     free (oldmess);
  834.     }
  835.   Msgbuff = newmess;
  836. }
  837.  
  838. /* ------------------------------------------------------------------------ */
  839.  
  840. static int laststatus = 0;
  841.  
  842. /*
  843.  * mfwrite() - The only fuction you'll need to call to write out
  844.  *             a midi file.
  845.  *
  846.  * format      0 - Single multi-channel track
  847.  *             1 - Multiple simultaneous tracks
  848.  *             2 - One or more sequentially independent
  849.  *                 single track patterns
  850.  * ntracks     The number of tracks in the file.
  851.  * division    This is kind of tricky, it can represent two
  852.  *             things, depending on whether it is positive or negative
  853.  *             (bit 15 set or not).  If  bit  15  of division  is zero,
  854.  *             bits 14 through 0 represent the number of delta-time
  855.  *             "ticks" which make up a quarter note.  If bit  15 of
  856.  *             division  is  a one, delta-times in a file correspond to
  857.  *             subdivisions of a second similiar to  SMPTE  and  MIDI
  858.  *             time code.  In  this format bits 14 through 8 contain
  859.  *             one of four values - 24, -25, -29, or -30,
  860.  *             corresponding  to  the  four standard  SMPTE and MIDI
  861.  *             time code frame per second formats, where  -29
  862.  *             represents  30  drop  frame.   The  second  byte
  863.  *             consisting  of  bits 7 through 0 corresponds the the
  864.  *             resolution within a frame.  Refer the Standard MIDI
  865.  *             Files 1.0 spec for more details.
  866.  * fp          This should be the open file pointer to the file you
  867.  *             want to write.  It will have be a global in order
  868.  *             to work with Mf_putc.
  869.  */
  870. /* mfwrite : returns <void> with input variables:
  871.  * format:
  872.  * ntracks:
  873.  * division:
  874.  * fp:
  875.  */
  876. void mfwrite (
  877.   int format,
  878.   int ntracks,
  879.   int division,
  880.   FILE *fp)
  881. {
  882.   int i;
  883.   void mf_write_track_chunk (), mf_write_header_chunk ();
  884.  
  885.   if (Mf_putc == NULLFUNC)
  886. mferror ("mfmf_write() called without setting Mf_putc");
  887.  
  888.   if (Mf_writetrack == NULLFUNC)
  889. mferror ("mfmf_write() called without setting Mf_mf_writetrack");
  890.  
  891.   laststatus = 0;
  892.  
  893.   /* every MIDI file starts with a header */
  894.   mf_write_header_chunk (format, ntracks, division);
  895.  
  896.   laststatus = 0;
  897.  
  898.   /* In format 1 files, the first track is a tempo map */
  899.   if (format == 1 && (Mf_writetempotrack)) {
  900.  
  901.     (*Mf_writetempotrack) ();
  902.     }
  903.  
  904.   /* The rest of the file is a series of tracks */
  905.   for (i = 0; i < ntracks; i++)
  906. mf_write_track_chunk (i, fp);
  907. }
  908.  
  909. /* ------------------------------------------------------------------------ */
  910.  
  911. /* mf_write_track_chunk : returns <void> with input variables:
  912.  * which_track:
  913.  * fp:
  914.  */
  915. void mf_write_track_chunk (
  916.   int which_track,
  917.   FILE *fp)
  918. {
  919.   unsigned long trkhdr, trklength;
  920.   long offset, place_marker;
  921.   void write16bit (), write32bit ();
  922.  
  923.  
  924.   laststatus = 0;
  925.  
  926.   trkhdr = MTrk;
  927.   trklength = 0;
  928.  
  929.   /* Remember where the length was written, because we don't
  930. know how long it will be until we've finished writing */
  931.   offset = ftell (fp);
  932.  
  933. #ifdef DEBUG
  934.   printf ("offset = %d\n", (int) offset);
  935. #endif
  936.  
  937.   /* Write the track chunk header */
  938.   write32bit (trkhdr);
  939.   write32bit (trklength);
  940.  
  941.   Mf_numbyteswritten = 0L;    /* the header's length doesn't count */
  942.  
  943.   if (Mf_writetrack) {
  944.  
  945.     (*Mf_writetrack) (which_track);
  946.     }
  947.  
  948.   /* mf_write End of track meta event */
  949. /* but this does not necessarily have a delta of 0, so
  950.  * I don't want to do it -- leave it up to the user of the
  951.  * library functions to do
  952.  *    --gl
  953. eputc(0);
  954. eputc(laststatus = meta_event);
  955. eputc(end_of_track);
  956.  
  957.      eputc(0);
  958.  */
  959.  
  960.   /* It's impossible to know how long the track chunk will be beforehand,
  961. so the position of the track length data is kept so that it can
  962. be written after the chunk has been generated */
  963.   place_marker = ftell (fp);
  964.  
  965.   /* This method turned out not to be portable because the
  966. parameter returned from ftell is not guaranteed to be
  967. in bytes on every machine */
  968.   /* track.length = place_marker - offset - (long) sizeof(track); */
  969.  
  970. #ifdef DEBUG
  971.   printf ("length = %d\n", (int) trklength);
  972. #endif
  973.  
  974.   if (fseek (fp, offset, 0) < 0)
  975. mferror ("error seeking during final stage of write");
  976.  
  977.   trklength = Mf_numbyteswritten;
  978.  
  979.   /* Re-mf_write the track chunk header with right length */
  980.   write32bit (trkhdr);
  981.   write32bit (trklength);
  982.  
  983.   fseek (fp, place_marker, 0);
  984. }
  985.  
  986. /* ------------------------------------------------------------------------ */
  987.  
  988. /* End gen_track_chunk() */
  989.  
  990. /* mf_write_header_chunk : returns <void> with input variables:
  991.  * format:
  992.  * ntracks:
  993.  * division:
  994.  */
  995. void mf_write_header_chunk (
  996.   int format,
  997.   int ntracks,
  998.   int division)
  999. {
  1000.   unsigned long ident, length;
  1001.   void write16bit (), write32bit ();
  1002.  
  1003.   ident = MThd;            /* Head chunk identifier                    */
  1004.   length = 6;            /* Chunk length                             */
  1005.  
  1006.   /* individual bytes of the header must be written separately
  1007. to preserve byte order across cpu types :-( */
  1008.   write32bit (ident);
  1009.   write32bit (length);
  1010.   write16bit (format);
  1011.   write16bit (ntracks);
  1012.   write16bit (division);
  1013. }
  1014.  
  1015. /* ------------------------------------------------------------------------ */
  1016.  
  1017. /* end gen_header_chunk() */
  1018.  
  1019. /*
  1020.  * mf_write_midi_event()
  1021.  *
  1022.  * Library routine to mf_write a single MIDI track event in the standard MIDI
  1023.  * file format. The format is:
  1024.  *
  1025.  *                    <delta-time><event>
  1026.  *
  1027.  * In this case, event can be any multi-byte midi message, such as
  1028.  * "note on", "note off", etc.
  1029.  *
  1030.  * delta_time - the time in ticks since the last event.
  1031.  * type - the type of meta event.
  1032.  * chan - The midi channel.
  1033.  * data - A pointer to a block of chars containing the META EVENT,
  1034.  *        data.
  1035.  * size - The length of the meta-event data.
  1036.  */
  1037. /* mf_write_midi_event : returns <int> with input variables:
  1038.  * delta_time:
  1039.  * type:
  1040.  * chan:
  1041.  * data:
  1042.  * size:
  1043.  */
  1044. int mf_write_midi_event (
  1045.   unsigned long delta_time,
  1046.   int type,
  1047.   int chan,
  1048.   char *data,
  1049.   unsigned long size)
  1050. {
  1051.   int i;
  1052.   unsigned char c;
  1053.  
  1054.   WriteVarLen (delta_time);
  1055.  
  1056.   /* all MIDI events start with the type in the first four bits,
  1057. and the channel in the lower four bits */
  1058.   if (type == system_exclusive || type == 0xf7) {
  1059.  
  1060.     c = type;
  1061.     laststatus = 0;
  1062.     }
  1063.   else
  1064. c = type | chan;
  1065.  
  1066.   if (chan > 15)
  1067. perror ("error: MIDI channel greater than 16\n");
  1068.  
  1069.   if (laststatus != c)
  1070. eputc (laststatus = c);
  1071.  
  1072.   if (type == system_exclusive || type == 0xf7)
  1073. WriteVarLen (size);
  1074.  
  1075.   /* write out the data bytes */
  1076.   for (i = 0; i < size; i++)
  1077. eputc (data[i]);
  1078.  
  1079.   return (size);
  1080. }
  1081.  
  1082. /* ------------------------------------------------------------------------ */
  1083.  
  1084. /* end mf_write MIDI event */
  1085. /*
  1086.  * mf_write_meta_event()
  1087.  *
  1088.  * Library routine to mf_write a single meta event in the standard MIDI
  1089.  * file format. The format of a meta event is:
  1090.  *
  1091.  *          <delta-time><FF><type><length><bytes>
  1092.  *
  1093.  * delta_time - the time in ticks since the last event.
  1094.  * type - the type of meta event.
  1095.  * data - A pointer to a block of chars containing the META EVENT,
  1096.  *        data.
  1097.  * size - The length of the meta-event data.
  1098.  */
  1099. /* mf_write_meta_event : returns <int> with input variables:
  1100.  * delta_time:
  1101.  * type:
  1102.  * data:
  1103.  * size:
  1104.  */
  1105. int mf_write_meta_event (
  1106.   unsigned long delta_time,
  1107.   unsigned char type,
  1108.   unsigned char *data,
  1109.   unsigned long size)
  1110. {
  1111.   int i;
  1112.  
  1113.   WriteVarLen (delta_time);
  1114.  
  1115.   /* This marks the fact we're writing a meta-event */
  1116.   eputc (laststatus = meta_event);
  1117.  
  1118.   /* The type of meta event */
  1119.   eputc (type);
  1120.  
  1121.   /* The length of the data bytes to follow */
  1122.   WriteVarLen (size);
  1123.  
  1124.   for (i = 0; i < size; i++) {
  1125.  
  1126.     if (eputc (data[i]) != data[i])
  1127.     return (-1);
  1128.     }
  1129.   return (size);
  1130. }
  1131.  
  1132. /* ------------------------------------------------------------------------ */
  1133.  
  1134. /* end mf_write_meta_event */
  1135. /* mf_write_tempo : returns <void> with input variables:
  1136.  * delta_time:
  1137.  * tempo:
  1138.  */
  1139. void mf_write_tempo (
  1140.   unsigned long delta_time,
  1141.   unsigned long tempo)
  1142. {
  1143.   /* Write tempo */
  1144.   /* all tempos are written as 120 beats/minute, */
  1145.   /* expressed in microseconds/quarter note     */
  1146.  
  1147.   WriteVarLen (delta_time);
  1148.   eputc (laststatus = meta_event);
  1149.   eputc (set_tempo);
  1150.  
  1151.   eputc (3);
  1152.   eputc ((unsigned) (0xff & (tempo >> 16)));
  1153.   eputc ((unsigned) (0xff & (tempo >> 8)));
  1154.   eputc ((unsigned) (0xff & tempo));
  1155. }
  1156.  
  1157. /* ------------------------------------------------------------------------ */
  1158.  
  1159. /* mf_write_seqnum : returns <void> with input variables:
  1160.  * delta_time:
  1161.  * seqnum:
  1162.  */
  1163. void mf_write_seqnum (
  1164.   unsigned long delta_time,
  1165.   unsigned seqnum)
  1166. {
  1167.  
  1168.   WriteVarLen (delta_time);
  1169.   eputc (laststatus = meta_event);
  1170.   eputc (0);
  1171.  
  1172.   eputc ((unsigned) (0xff & (seqnum >> 8)));
  1173.   eputc ((unsigned) (0xff & seqnum));
  1174. }
  1175.  
  1176. /* ------------------------------------------------------------------------ */
  1177.  
  1178. /* mf_sec2ticks : returns <unsigned long> with input variables:
  1179.  * secs:
  1180.  * division:
  1181.  * tempo:
  1182.  */
  1183. unsigned long mf_sec2ticks (
  1184.   double secs,
  1185.   int division,
  1186.   unsigned long tempo)
  1187. {
  1188.   return (unsigned long) (((secs * 1000.0) / 4.0 * division) / tempo);
  1189. }
  1190.  
  1191. /* ------------------------------------------------------------------------ */
  1192.  
  1193. /*
  1194.  * Write multi-length bytes to MIDI format files
  1195.  */
  1196. /* WriteVarLen : returns <void> with input variables:
  1197.  * value:
  1198.  */
  1199. void WriteVarLen (unsigned long value)
  1200. {
  1201.   unsigned long buffer;
  1202.  
  1203.   buffer = value & 0x7f;
  1204.   while ((value >>= 7) > 0) {
  1205.  
  1206.     buffer <<= 8;
  1207.     buffer |= 0x80;
  1208.     buffer += (value & 0x7f);
  1209.     }
  1210.   while (1) {
  1211.  
  1212.     eputc ((unsigned) (buffer & 0xff));
  1213.  
  1214.     if (buffer & 0x80)
  1215.     buffer >>= 8;
  1216.     else
  1217.     return;
  1218.     }
  1219. }
  1220.  
  1221. /* ------------------------------------------------------------------------ */
  1222.  
  1223. /* end of WriteVarLen */
  1224. /*
  1225.  * This routine converts delta times in ticks into seconds. The
  1226.  * else statement is needed because the formula is different for tracks
  1227.  * based on notes and tracks based on SMPTE times.
  1228.  *
  1229.  */
  1230. /* mf_ticks2sec : returns <double> with input variables:
  1231.  * ticks:
  1232.  * division:
  1233.  * tempo:
  1234.  */
  1235. double mf_ticks2sec (
  1236.   unsigned long ticks,
  1237.   int division,
  1238.   unsigned long tempo)
  1239. {
  1240.   double smpte_format, smpte_resolution;
  1241.  
  1242.   if (division > 0)
  1243. return ((double) (((double) (ticks) * (double) (tempo)) / ((double) (division) * 1000000.0)));
  1244.   else {
  1245.  
  1246.     smpte_format = upperbyte (division);
  1247.     smpte_resolution = lowerbyte (division);
  1248.     return (double) ((double) ticks / (smpte_format * smpte_resolution * 1000000.0));
  1249.     }
  1250. }
  1251.  
  1252. /* ------------------------------------------------------------------------ */
  1253.  
  1254. /* end of ticks2sec() */
  1255.  
  1256. /*
  1257.  * write32bit()
  1258.  * write16bit()
  1259.  *
  1260.  * These routines are used to make sure that the byte order of
  1261.  * the various data types remains constant between machines. This
  1262.  * helps make sure that the code will be portable from one system
  1263.  * to the next.  It is slightly dangerous that it assumes that longs
  1264.  * have at least 32 bits and ints have at least 16 bits, but this
  1265.  * has been true at least on PCs, UNIX machines, and Macintosh's.
  1266.  *
  1267.  */
  1268. /* write32bit : returns <void> with input variables:
  1269.  * data:
  1270.  */
  1271. void write32bit (unsigned long data)
  1272. {
  1273.   eputc ((unsigned) ((data >> 24) & 0xff));
  1274.   eputc ((unsigned) ((data >> 16) & 0xff));
  1275.   eputc ((unsigned) ((data >> 8) & 0xff));
  1276.   eputc ((unsigned) (data & 0xff));
  1277. }
  1278.  
  1279. /* ------------------------------------------------------------------------ */
  1280.  
  1281. /* write16bit : returns <void> with input variables:
  1282.  * data:
  1283.  */
  1284. void write16bit (int data)
  1285. {
  1286.   eputc ((unsigned) ((data & 0xff00) >> 8));
  1287.   eputc ((unsigned) (data & 0xff));
  1288. }
  1289.  
  1290. /* ------------------------------------------------------------------------ */
  1291.  
  1292. /* write a single character and abort on error */
  1293. /* eputc : returns <static int> with input variables:
  1294.  * c:
  1295.  */
  1296. static int eputc (unsigned char c)
  1297. {
  1298.   int return_val;
  1299.  
  1300.   if ((Mf_putc) == NULLFUNC) {
  1301.  
  1302.     mferror ("Mf_putc undefined");
  1303.     return (-1);
  1304.     }
  1305.  
  1306.   return_val = (*Mf_putc) (c);
  1307.  
  1308.   if (return_val == EOF)
  1309. mferror ("error writing");
  1310.  
  1311.   Mf_numbyteswritten++;
  1312.   return (return_val);
  1313. }
  1314.  
  1315. /* ------------------------------------------------------------------------ */
  1316.  
  1317.